#!/bin/sh -efu
#
# Copyright (C) 2009  Alexey Gladkov <legion@altlinux.org>
# Copyright (C) 2009  Alexey I. Froloff <raorn@altlinux.org>
# Copyright (C) 2017  Dmitry V. Levin <ldv@altlinux.org>
#
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#

. gear-update-sh-functions

source_type="${PROG##gear-update-src-}"

check_source_type()
{
	local file_type
	file_type="$(file -b "$gear_update_source")"

	if [ "$source_type" = 'cpio' ]; then
		case "$file_type" in
			*cpio\ archive*) return 0 ;;
		esac
	fi

	file_type="$(file -bz "$gear_update_source")"

	case "$file_type" in
		*cpio\ archive\ *)
			file_type="${file_type##*cpio archive }" ;;
		*) return 2 ;;
	esac

	case "$file_type" in
		*\ compressed\ data*)
			file_type="${file_type% compressed data*}" ;;
		*) return 2 ;;
	esac

	case "$source_type" in
		cpio.bz2)
			case "$file_type" in
				*bzip2) return 0 ;;
			esac
			;;
		cpio.gz)
			case "$file_type" in
				*gzip) return 0 ;;
			esac
			;;
		cpio.xz)
			case "$file_type" in
				*xz|*XZ) return 0 ;;
			esac
			;;
		cpio.zst)
			case "$file_type" in
				*zstd|*Zstandard) return 0 ;;
			esac
			;;
	esac

	return 2
}

list_source()
{
	local compress

	case "$source_type" in
		cpio)     compress='cat' ;;
		cpio.xz)  compress='unxz -c' ;;
		cpio.gz)  compress='gunzip -c' ;;
		cpio.bz2) compress='bunzip2 -c' ;;
		cpio.zst) compress='unzstd -qc' ;;
		*)
			fatal "$gear_update_source: unrecognized source type: $source_type"
			;;
	esac
	$compress "$gear_update_source" |
		cpio --quiet -t
}

unpack_source()
{
	local compress

	case "$source_type" in
		cpio)     compress='cat' ;;
		cpio.xz)  compress='unxz -c' ;;
		cpio.gz)  compress='gunzip -c' ;;
		cpio.bz2) compress='bunzip2 -c' ;;
		cpio.zst) compress='unzstd -qc' ;;
		*)
			fatal "$gear_update_source: unrecognized source type: $source_type"
			;;
	esac

	install_cleanup_handler cleanup_workdir
	workdir="$(mktemp -d "$PROG.XXXXXXXXX")"

	cd "$workdir"
	$compress "$gear_update_source" |
		cpio --quiet -id ${gear_update_subdir:+"$gear_update_subdir/*"}
	chmod -R u+rwX,go-w .
	cd - >/dev/null

	validate_destdir "$workdir/$gear_update_subdir" "$gear_update_destdir"
	update_destdir move "$workdir/$gear_update_subdir" "$gear_update_destdir"
}

gear_update_handler "$@"
